﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Yule8xCommon.Applib
{
    public class DataTableUtil
    {
        public static object GetObject(DataTable dt, string field, object defv = null)
        {
            if (null == dt || dt.Rows.Count < 1 || !dt.Columns.Contains(field))
            {
                return defv;
            }
            object value = dt.Rows[0][field];
            return DBNull.Value == value ? defv : value;
        }
        public static int GetInteger(DataTable dt, string field, int defv = 0)
        {
            object value = GetObject(dt, field);
            int outVal;
            return null != value && int.TryParse(value.ToString(), out outVal) ? outVal : defv;
        }
        public static decimal GetDecimal(DataTable dt, string field, decimal defv = 0)
        {
            object value = GetObject(dt, field);
            decimal outVal;
            return null != value && decimal.TryParse(value.ToString(), out outVal) ? outVal : defv;
        }
        /// <summary>
        /// 0001-1-1 00:00:01
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static DateTime GetDateTime(DataTable dt, string field)
        {
            object value = GetObject(dt, field);
            DateTime outVal;
            return null != value && DateTime.TryParse(value.ToString(), out outVal) ? outVal : default(DateTime);
        }

        public static string GetString(DataTable dt, string field)
        {
            object value = GetObject(dt, field);
            return null == value ? string.Empty : value.ToString();
        }
    }
}